//
//  NSObject+Helper.m
//  Kaagad Peso
//
//  Created by ZhengChengFeng on 2024/10/15.
//

#import "NSObject+Helper.h"

@implementation NSObject (Helper)

- (UIViewController *)currentViewController{

    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    if (@available(iOS 14,*)) {
        keyWindow =  [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    }
    
    if ([keyWindow.rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tab =(UITabBarController *) keyWindow.rootViewController;
        if ([tab.selectedViewController isKindOfClass:[UINavigationController class]]) {
            UINavigationController *nav = (UINavigationController *)tab.selectedViewController;
            return [nav.viewControllers lastObject];
        } else {
            return tab.selectedViewController;
        }
    }
    else if ([keyWindow.rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)keyWindow.rootViewController;
        return [nav.viewControllers lastObject];
    }
    return nil;
    
}

- (UIViewController *)getCurrentVC{
    UIViewController *resultVC = nil;
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    if (@available(iOS 14,*)) {
        keyWindow =  [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    }
    
    if (keyWindow.windowLevel != UIWindowLevelNormal) {
        NSArray *windowAry = [UIApplication sharedApplication].windows;
        for (UIWindow *win in windowAry) {
            if (win.windowLevel == UIWindowLevelNormal) {
                keyWindow = win;
                break;
            }
        }
    }
    resultVC = keyWindow.rootViewController;

    if (resultVC.presentedViewController) {
        resultVC = resultVC.presentedViewController;
    }
    
    if ([resultVC isKindOfClass:[UITabBarController class]]) {
        resultVC = [(UITabBarController *)resultVC selectedViewController];
    }
    
    if ([resultVC isKindOfClass:[UINavigationController class]]) {
        resultVC = [(UINavigationController *)resultVC visibleViewController];
    }
    
    return resultVC;
}

+ (CGFloat)vg_statusBarHeight{
    if (@available(iOS 13.0, *)) {
        NSSet *set = [UIApplication sharedApplication].connectedScenes;
        UIWindowScene *windowScene = [set anyObject];
        UIStatusBarManager *statusBarManager = windowScene.statusBarManager;
        return statusBarManager.statusBarFrame.size.height;
    } else {
        return [UIApplication sharedApplication].statusBarFrame.size.height;
    }
}

@end
